package net.zjitc.servlet.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FileUpLoadServlet" ,urlPatterns = "/fileUploadServlet")
public class FileUpLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //第三方的包：
        //request.setCharacterEncoding("UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //upload.setFileSizeMax(1024*10);
        //编码
        request.setCharacterEncoding("UTF-8");
        try {
            //
            List<FileItem> itemList = upload.parseRequest(request);
            //
            //response.setCharacterEncoding("UTF-8");
            //如果响应还是乱码，请用以下方法
            response.setContentType("text/html;charset=UTF-8");

            PrintWriter writer = response.getWriter();
            for (FileItem item: itemList) {
                if (item.isFormField()){ //普通字段
                    String fieldName = item.getFieldName();
                    String value = item.getString("UTF-8");
                    //取到的内容输出到页面
                    writer.write(fieldName+" : "+value+"<br/>");
                }else { //文件
                    String name = item.getName();//文件名
                    //InputStream inputStream = item.getInputStream();//文件内容--IO流
                   //生成UUID:解决文件名重复的问题
                    String uuid = UUID.randomUUID().toString();
                    uuid= uuid.replace("-","");
                    //保存到本地:保存当前项目下,完整的路径
                    String path = this.getServletContext().getRealPath("/uploads");
                    String filename = uuid+"-"+name;
                    File file = new File(path,filename);
                    item.write(file);

                    //路径存储到数据库： path=  /uploads/filename

                    //地址：如果放进去的时候不带/即： uploads/filename，那么前端取的时候直接取就行，src后面就行，
                    //如果放进去的是：/uploads/filename,那么取的时候前面需要加 contextPath，即项目路径

                    writer.write("文件已经保存");
                    // uuid+shop.sql
                }
            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
